package com.ysstech.valuation.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysstech.common.entity.PageBean;
import com.ysstech.common.util.BigDecimalUtil;
import com.ysstech.common.util.DateUtil;
import com.ysstech.common.util.resultutil.RestResult;
import com.ysstech.common.util.resultutil.ResultCode;
import com.ysstech.valuation.entity.*;
import com.ysstech.valuation.enums.ValuationTotalEnum;
import com.ysstech.valuation.feign.FeignFinanceService;
import com.ysstech.valuation.feign.entity.Balance;
import com.ysstech.valuation.feign.entity.Subject;
import com.ysstech.valuation.mapper.ValuationMapper;
import com.ysstech.valuation.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lishuangliang
 * @since 2021-05-11
 */
@Slf4j
@Service
public class ValuationServiceImpl extends ServiceImpl<ValuationMapper, Valuation> implements ValuationService {
    @Autowired
    private ValuationMapper valuationMapper;
    @Autowired
    private QuotationService quotationService;
    @Autowired
    private ValuationTotalService valuationTotalService;
    @Autowired
    private FeignFinanceService feignFinanceService;

    /**
     * 查询估值表列表信息
     *
     * @param valuation
     * @param pageBean
     * @return
     * @throws Exception
     */
    public PageBean<Valuation> queryAllValuation(Valuation valuation, PageBean pageBean) throws Exception {
        QueryWrapper<Valuation> wrapper = this.getQueryWrapper(valuation);
        IPage pageBalance = valuationMapper.queryValuation(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), wrapper);
        this.switchedListBalance(pageBalance.getRecords(), valuation);
        return new PageBean<>(pageBalance);
    }

    /**
     * 类型，机构等中文的转换
     *
     * @param list
     * @return
     * @throws Exception
     */
    public List<Valuation> switchedListBalance(List<Valuation> list, Valuation valuation) throws Exception {
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        for (Valuation val : list) {
            if (null == val) {
                continue;
            }
            // 单位成本
            if (BigDecimalUtil.compareTo(val.getAmount(), BigDecimal.ZERO) > 0) {
                val.setUnitCost(BigDecimalUtil.divide(val.getCost(), val.getAmount(), 8));
            }
            // 估值增值
            val.setValuationAppreciation(BigDecimalUtil.subtract(val.getMarketValue(), val.getCost()));
            // 明细科目open
            if ("0".equals(val.getParentId())) {
                val.set_parentId(null);
            } else {
                val.set_parentId(val.getParentId());
            }
            if (1 == val.getDetailed()) {
                val.setState("open");
            } else {
                val.setState("closed");
            }
            val.setChecked(false);
            val.setIconCls("icon-bricks");
            QueryWrapper<ValuationTotal> wrapper = new QueryWrapper<>();
            wrapper.eq("FDATE", DateUtil.strToLocalDate(valuation.getSelfdate()));
            wrapper.eq("ACCOUNT_ID", val.getAccountId());
            // 净值编码
            wrapper.eq("TYPE", ValuationTotalEnum.NET_VALUE.getCode());
            // 获取资产净值
            ValuationTotal valuationTotal = valuationTotalService.getOne(wrapper);
            if (null == valuationTotal || null == valuationTotal.getMarketValue()) {
                continue;
            }
            // 成本占净值比例
            val.setCostRate(BigDecimalUtil.divide(val.getCost(), valuationTotal.getMarketValue(), 8));
            // 市值占净值比例
            val.setMarketValueRate(BigDecimalUtil.divide(val.getCost(), valuationTotal.getMarketValue(), 8));
        }
        return list;
    }

    /**
     * 查询条件
     *
     * @param valuation
     * @return
     * @throws Exception
     */
    private QueryWrapper<Valuation> getQueryWrapper(Valuation valuation) throws Exception {
        QueryWrapper<Valuation> wrapper = new QueryWrapper<>();
        //wrapper.orderByAsc("FDATE,ACCOUNT_ID,SUBJECT_CODE,AUXILARY_CDOE");
        if (null == valuation) {
            return wrapper;
        }
        if (StringUtils.isNotBlank(valuation.getSelfdate())) {
            wrapper.eq("FDATE", valuation.getSelfdate());
        }
        return wrapper;
    }


    /**
     * 生成估值表
     *
     * @param valuation
     * @throws Exception
     */
    public void produceValuation(Valuation valuation) throws Exception {
        if (null == valuation || StringUtils.isBlank(valuation.getSelfdate()) || StringUtils.isBlank(valuation.getAccountId())) {
            log.info("没有获取到需要生成估值表的数据信息！");
            return;
        }
        QueryWrapper<Valuation> wrapper = new QueryWrapper<>();
        wrapper.eq("FDATE", DateUtil.strToLocalDate(valuation.getSelfdate()));
        wrapper.eq("ACCOUNT_ID", valuation.getAccountId());
        this.remove(wrapper);
        // 获取余额表数据 取的都是凭证对应科目，核算到最明细的科目
        List<Balance> list = feignFinanceService.queryBalanceByValuation(valuation.getAccountId(), valuation.getSelfdate());
        // List<Map<String, String>> list = (List<Map<String, String>>) result.getData();
        if (CollectionUtils.isEmpty(list)) {
            log.info("没有获取到余额表数据！" + valuation.getAccountId() + valuation.getSelfdate());
            return;
        }
        List<Valuation> listadd = new ArrayList<>();
        for (Balance balance : list) {
            if (null == balance) {
                continue;
            }
            Valuation valuationAdd = new Valuation();
            valuationAdd.setSelfdate(valuation.getSelfdate());
            //市值 默认余额
            valuationAdd.setMarketValue(balance.getEndBalance());
            // 核算数量的科目 计算科目市值
            if (1 == balance.getAmount()) {
                this.getMarketValue(balance.getSecuritiesCode(), balance.getEndAmount(), valuationAdd);
            }
            valuationAdd.setAssetsType(balance.getAssetsType());
            valuationAdd.setId(DateUtil.generateUUID());
            valuationAdd.setFdate(balance.getFdate());
            valuationAdd.setAccountId(balance.getAccountId()); // 基金编码
            valuationAdd.setSubjectId(balance.getSubjectId()); // 科目编码
            valuationAdd.setCost(balance.getEndBalance()); // 成本
            valuationAdd.setAmount(balance.getEndAmount()); // 数量
            valuationAdd.setAddTime(LocalDateTime.now());
            valuationAdd.setAssetsType(balance.getAssetsType());
            listadd.add(valuationAdd);
        }
        //保存估值表明细项
        if (CollectionUtils.isEmpty(listadd)) {
            log.error("没有获取到要插入估值表的明细数据!");
            return;
        }
        // 统计估值表信息
        this.handleValuation(listadd);
        // 处理合计项
        valuationTotalService.insertValuationTotal(listadd, valuation);
    }


    /**
     * 估值表将明细数据汇总上去
     */
    private void handleValuation(List<Valuation> addlist) throws Exception {
        if (CollectionUtils.isEmpty(addlist)) {
            return;
        }
        // 获取所有科目信息
        Map<String, Subject> sujbectMap = feignFinanceService.getSubjectMap();
        if (CollectionUtils.isEmpty(sujbectMap)) {
            return;
        }
        Map<String, Valuation> map = new HashMap<>();
        // 汇集上级科目
        for (Valuation val : addlist) {
            if (null == val) {
                continue;
            }
            recursionAdjust(val, sujbectMap, map);
        }
        for (Map.Entry<String, Valuation> info : map.entrySet()) {
            if (null == info.getValue()) {
                continue;
            }
            addlist.add(info.getValue());
        }
        this.saveBatch(addlist);
    }

    private void recursionAdjust(Valuation valuation, Map<String, Subject> sujbectMap, Map<String, Valuation> map) throws Exception {
        if (CollectionUtils.isEmpty(sujbectMap)) {
            return;
        }
        Subject subject = sujbectMap.get(valuation.getSubjectId());
        if (null == subject) {
            return;
        }
        String parentId = subject.getParentId();
        if (StringUtils.isBlank(parentId) || "0".equals(parentId)) {
            return;
        }
        if (map.containsKey(parentId)) {
            Valuation bean = map.get(parentId);
            bean.setAmount(bean.getAmount().add(valuation.getAmount())); //数量
            bean.setCost(bean.getCost().add(valuation.getCost())); //成本
            bean.setMarketValue(bean.getMarketValue().add(valuation.getMarketValue()));//市值
            map.put(parentId, bean);
            recursionAdjust(bean, sujbectMap, map);
        } else {
            Valuation sumValuation = new Valuation();
            sumValuation.setId(DateUtil.generateUUID());
            sumValuation.setFdate(valuation.getFdate());
            sumValuation.setAccountId(valuation.getAccountId());
            sumValuation.setAmount(valuation.getAmount());
            sumValuation.setCost(valuation.getCost());
            sumValuation.setMarketValue(valuation.getMarketValue());
            sumValuation.setSubjectId(parentId);
            sumValuation.setAssetsType(valuation.getAssetsType());
            map.put(parentId, sumValuation);
            recursionAdjust(sumValuation, sujbectMap, map);
        }
    }

    /**
     * 获取证券的行情 计算市值 并且设置的停牌信息
     *
     * @param securitiesCode
     * @param endAmount
     * @param valuationAdd
     * @throws Exception
     */
    private void getMarketValue(String securitiesCode, BigDecimal endAmount, Valuation valuationAdd) throws Exception {
        if (StringUtils.isBlank(securitiesCode)) {
            return;
        }
        Quotation quotation = queryQuotation(valuationAdd.getSelfdate(), securitiesCode);
        if (null == quotation || null == quotation.getQuotationClosingPrice()) {
            valuationAdd.setSuspendedInfo("【无行情】");
            return;
        }
        //市值 = 数量*行情价格
        valuationAdd.setMarketValue(endAmount.multiply(quotation.getQuotationClosingPrice()));
        if (DateUtil.differentDaysByString(valuationAdd.getSelfdate(), DateUtil.localDateToStr(quotation.getFdate())) == 0) {
            valuationAdd.setSuspendedInfo("【正常交易】");
        } else {
            valuationAdd.setSuspendedInfo("【停牌】" + DateUtil.localDateToStr(quotation.getFdate()));
        }
        return;
    }

    /**
     * 从reids缓存取出来的数据放到map缓存，防止每次都去redis取
     *
     * @param fdate
     * @return
     * @throws Exception
     */
    public Quotation queryQuotation(String fdate, String securitiesCode) throws Exception {
        Map<String, List<Quotation>> map = quotationService.queryQuotationCache(DateUtil.strToLocalDate(fdate));
        List<Quotation> listhq = map.get(fdate + "\t" + securitiesCode);
        if (CollectionUtils.isEmpty(listhq)) {
            return null;
        }
        Quotation quotation = listhq.get(0);
        if (null == quotation) {
            return null;
        }
        return listhq.get(0);
    }


}
